package com.bawei.module_mine.ui

import android.os.Bundle
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_common.aop.LoginManager
import com.bawei.lib_net.datastore.DataStoreUtils
import com.bawei.module_mine.R
import com.bawei.module_mine.common.ConstanstValue
import com.bawei.module_mine.common.GsonUtil
import com.bawei.module_mine.databinding.ActivityQuickLoginBinding
import com.bawei.module_mine.intent.QuickLoginIntent
import com.bawei.module_mine.state.QuickLoginState
import com.bawei.module_mine.viewmodel.QuickLoginViewModel
import kotlinx.coroutines.launch
import cn.jiguang.verifysdk.api.JVerificationInterface
import cn.jiguang.verifysdk.api.VerifyListener
import android.content.Intent

@Route(path = "/module_mine/QuickLoginActivity")
class QuickLoginActivity : AppCompatActivity() {
    
    private lateinit var binding: ActivityQuickLoginBinding
    private var viewModel: QuickLoginViewModel? = null
    private var currentPhoneNumber: String = ""
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityQuickLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        initViewModel()
        initView()
        initEvent()
        handleState()
        
        // 页面启动时检查极光一键登录认证服务
        checkJVerificationEnable()
        // 页面启动时自动检测认证服务并拉取手机号
        // checkAuthService() // 已注释：不再自动获取手机号
    }
    
    override fun onDestroy() {
        super.onDestroy()
        // 通知LoginManager登录页面已关闭
        LoginManager.onLoginPageClosed()
        Log.d("QuickLoginActivity", "一键登录页面已关闭")
    }
    
    override fun onPause() {
        super.onPause()
        Log.d("QuickLoginActivity", "一键登录页面暂停")
    }
    
    override fun onResume() {
        super.onResume()
        Log.d("QuickLoginActivity", "一键登录页面恢复")
    }
    
    override fun onBackPressed() {
        Log.d("QuickLoginActivity", "用户点击返回键")
        // 确保在返回时也清理状态
        LoginManager.onLoginPageClosed()
        super.onBackPressed()
    }
    
    private fun initViewModel() {
        viewModel = QuickLoginViewModel()
    }

    private fun initView() {
        Log.d("QuickLoginActivity", "初始化界面")
        // 设置状态栏颜色
        window.statusBarColor = getColor(R.color.colorPrimary)
        binding.tvPhone.text = viewModel?.phone ?:  "没获取到手机号"
    }
    
    private fun initEvent() {
        // 关闭按钮
        binding.ivClose.setOnClickListener {
            Log.d("QuickLoginActivity", "用户点击关闭")
            finish()
        }
        
        // 一键登录按钮
        binding.btnOneKeyLogin.setOnClickListener {
            Log.d("QuickLoginActivity", "用户点击一键登录")
            JVerificationInterface.loginAuth(this, true, object : VerifyListener {
                override fun onResult(code: Int, content: String?, operator: String?) {
                    runOnUiThread {
                        if (code == 6000 && !content.isNullOrEmpty()) {
                            val loginToken = try {
                                org.json.JSONObject(content).optString("loginToken", content)
                            } catch (e: Exception) {
                                content
                            }
                            lifecycleScope.launch {
                                viewModel?.intents?.send(QuickLoginIntent.OneKeyLogin(loginToken))
                            }
                        } else {
                            showMsg("一键登录失败, code=$code, $content")
                        }
                    }
                }
            })
        }
        
        // 其他手机号登录
        binding.tvOtherLogin.setOnClickListener {
            Log.d("QuickLoginActivity", "用户点击其他手机号登录")
            // 先标记当前页面关闭，然后跳转到普通登录页面
            LoginManager.onLoginPageClosed()
            // 跳转到普通登录页面
            ARouter.getInstance()
                .build("/module_mine/LoginActivity")
                .navigation()
            finish()
        }
        
        // 第三方登录
        binding.ivWechat.setOnClickListener {
            Log.d("QuickLoginActivity", "用户点击微信登录")
            showMsg("微信登录功能开发中")
        }
        
        binding.ivApple.setOnClickListener {
            Log.d("QuickLoginActivity", "用户点击Apple登录")
            showMsg("Apple登录功能开发中")
        }
        
        binding.ivQq.setOnClickListener {
            Log.d("QuickLoginActivity", "用户点击QQ登录")
            showMsg("QQ登录功能开发中")
        }
    }
    
    private fun handleState() {
        lifecycleScope.launch {
            viewModel?.state?.collect { state ->
                when (state) {
                    is QuickLoginState.QuickLoginInit -> {
                        Log.d("QuickLoginActivity", "一键登录状态初始化")
                        resetButtonState()
                    }
                    
                    is QuickLoginState.Loading -> {
                        Log.d("QuickLoginActivity", "加载状态: ${state.message}")
                        showLoadingState(state.message)
                    }
                    
                    // 已注释：不再处理PhoneNumberSuccess分支
//                    is QuickLoginState.PhoneNumberSuccess -> {
//                        Log.d("QuickLoginActivity", "获取手机号成功: ${state.phoneNumber}")
//                        currentPhoneNumber = state.phoneNumber
//                        binding.tvPhone.text = state.phoneNumber
//                        resetButtonState()
//                    }
                    
                    // 已注释：不再处理PhoneNumberFailed分支
//                    is QuickLoginState.PhoneNumberFailed -> {
//                        Log.d("QuickLoginActivity", "获取手机号失败: ${state.message}")
//                        showMsg(state.message)
//                        resetButtonState()
//                    }
                    
                    is QuickLoginState.OneKeyLoginSuccess -> {
                        try {
                            Log.d("QuickLoginActivity", "一键登录成功")
                            
                            val token = state.result.token
                            if (token.isNullOrEmpty()) {
                                Log.e("QuickLoginActivity", "登录成功但token为空")
                                showMsg("登录成功但token异常，请重试")
                                resetButtonState()
                                return@collect
                            }
                            
                            // 展示手机号（用username字段）
                            val phone = state.result.username
                            binding.tvPhone.text = phone ?: "未获取到手机号"
                            currentPhoneNumber = phone ?: ""
                            
                            // 保存登录状态
                            LoginManager.onLoginSuccess(token)
                            
                            // 保存用户信息
                            try {
                                DataStoreUtils.putData(ConstanstValue.CURRENT_USER,
                                    GsonUtil.toJsonWtihNullField(state.result))
                                DataStoreUtils.putData(ConstanstValue.TOKEN, token)
                            } catch (e: Exception) {
                                Log.e("QuickLoginActivity", "保存用户信息失败: ${e.message}", e)
                                DataStoreUtils.putData(ConstanstValue.TOKEN, token)
                            }
                            
                            showMsg("登录成功")
                            finish()
                            
                        } catch (e: Exception) {
                            Log.e("QuickLoginActivity", "处理登录成功状态异常: ${e.message}", e)
                            showMsg("登录成功但保存信息失败")
                            resetButtonState()
                        }
                    }
                    
                    is QuickLoginState.OneKeyLoginFailed -> {
                        Log.d("QuickLoginActivity", "一键登录失败: ${state.message}")
                        showMsg(state.message)
                        resetButtonState()
                    }
                    
                    is QuickLoginState.AuthServiceResult -> {
                        Log.d("QuickLoginActivity", "认证服务检查结果: ${state.message}")
                        if (state.isAvailable) {
                            // getPhoneNumber() // 已注释：不再自动获取手机号
                        } else {
                            showMsg(state.message)
                            // 禁用一键登录按钮
                            binding.btnOneKeyLogin.isEnabled = false
                            binding.btnOneKeyLogin.text = "认证服务不可用"
                        }
                    }
                    else -> {
                        // 其它未处理的状态，保持静默或日志
                    }
                }
            }
        }
    }
    
    /**
     * 检查认证服务
     */
//    private fun checkAuthService() {
//        lifecycleScope.launch {
//            try {
//                viewModel?.intents?.send(QuickLoginIntent.CheckAuthService)
//            } catch (e: Exception) {
//                Log.e("QuickLoginActivity", "检查认证服务异常: ", e)
//                showMsg("检查认证服务失败")
//            }
//        }
//    }
    
    /**
     * 获取手机号
     */
//    private fun getPhoneNumber() {
//        lifecycleScope.launch {
//            try {
//                viewModel?.intents?.send(QuickLoginIntent.GetPhoneNumber)
//            } catch (e: Exception) {
//                Log.e("QuickLoginActivity", "获取手机号异常: ", e)
//                showMsg("获取手机号失败")
//            }
//        }
//    }
    
//    /**
//     * 执行一键登录
//     */
//    private fun performOneKeyLogin() {
//        lifecycleScope.launch {
//            try {
//                viewModel?.intents?.send(QuickLoginIntent.OneKeyLogin(currentPhoneNumber))
//            } catch (e: Exception) {
//                Log.e("QuickLoginActivity", "执行一键登录异常: ${e.message}", e)
//                showMsg("登录请求失败，请重试")
//                resetButtonState()
//            }
//
//        }
//    }
    
    /**
     * 显示加载状态
     */
    private fun showLoadingState(message: String) {
        binding.btnOneKeyLogin.isEnabled = false
        binding.btnOneKeyLogin.text = message
    }
    
    /**
     * 重置按钮状态
     */
    private fun resetButtonState() {
        binding.btnOneKeyLogin.isEnabled = true
        binding.btnOneKeyLogin.text = "本机号码一键登录"
    }
    
    /**
     * 显示消息
     */
    private fun showMsg(message: String) {
        // 这里可以使用Toast或其他提示方式
        Log.d("QuickLoginActivity", "显示消息: $message")
        // 实际项目中可以使用Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
    }

    private fun checkJVerificationEnable() {
        val enable = JVerificationInterface.checkVerifyEnable(this)
        if (!enable) {
            showMsg("本机认证服务不可用")
            binding.btnOneKeyLogin.isEnabled = false
            binding.btnOneKeyLogin.text = "认证服务不可用"
        }
    }

    /**
     * 示例：从商品详情页或购物车跳转到确认订单页
     */
    private fun gotoConfirmOrder(productId: String, quantity: Int) {
        com.alibaba.android.arouter.launcher.ARouter.getInstance()
            .build("/module_mine/ConfirmOrderActivity")
            .withString("productId", productId)
            .withInt("quantity", quantity)
            .navigation(this)
    }
}